import { ref, reactive, onMounted, nextTick } from 'vue';
import { emitter } from "@/utils/mitt";
import { ElMessage, FormInstance } from "element-plus";
import { SpliceDate } from "@/utils/public/method"
import {
  ProOBDDataObtaAuth,
  ProOBDDataObtainEmp,
  ProProtectionGetOBDData,
  ProProtectionGetPINumber,
  ProOBDDataObtainEmpState,
  ProProtectionGetCustomDetail,
  ProProtectionOBDDataEmpApply,
  ProProtectionGetApplyHealth,
  ProProtectionGetAssured,
  ProProtectionGetHealth
} from "@/api/stu/InsuranceData";
import { type PaginationProps } from "@pureadmin/table";
import qs from 'qs';
import { useRoute } from "vue-router";
export function useDataManagement() {
  const route = useRoute();
  const columns = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "保单号",
      prop: "piNumber",
    },
    {
      label: "投保人",
      prop: "piApplicant",
    },
    {
      label: "保险产品名称",
      prop: "ppName",
    },
    {
      label: "保险类型",
      prop: "pType",
    }, {
      label: "操作",
      fixed: "right",
      width: 220,
      slot: "operation"
    }

  ];
  const dataList = ref([]);
  const loading = ref(true);
  const dataLists = ref([]);
  const loadings = ref(true);
  const DialogVisible = ref(false);
  const statement = ref(false);
  const CartODB = ref(false);
  const CartODBData = reactive({
    empowerTime: "",
    datas: []
  });
  const ShowDetails = ref(false);
  const MyDetails = reactive<any>({
    applyTime: "",
    datas: []
  })
  const btnloading = ref<boolean>(false);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 30,
    currentPage: 1,
    pageSizes: [10, 30, 50, 100],
    background: true
  });
  const paginations = reactive<PaginationProps>({
    total: 0,
    pageSize: 30,
    currentPage: 1,
    pageSizes: [10, 30, 50, 100],
    background: true
  });
  const newform = reactive<any>({
    PINumber: "",
    ApplyTime: ""
  })
  const stubimfrom = ref()
  const rules = {
    PINumber: [
      { required: true, message: '请选择保单号', trigger: ['change', 'blur'] },
    ],
    ApplyTime: [
      { required: true, message: '请选择日期', trigger: ['change', 'blur'] },
    ],
  };
  const PINumber = ref([]);
  const SendDataName = ref<any>({})// 授权名称
  const SendDataDate = ref(undefined);// 授权时间
  function handleSizeChange() { GetListData() }
  function handleCurrentChange() { GetListData() };
  function handleSizeChanges() { GetListDatas() }
  function handleCurrentChanges() { GetListDatas() };
  // 申请授权
  async function stubim_from(row) {
    (row as any).validate(async valid => {
      if (!valid) return;
      const data = {
        "taskId": route.query.taskId,
        "planId": route.query.planId,
        piApplicant: newform.PINumber.piApplicant,
        piNumber: newform.PINumber.piNumber,
        ppName: newform.PINumber.ppName,
        applyTime: newform.ApplyTime
      }
      btnloading.value = true;
      const res = await ProProtectionOBDDataEmpApply(data);
      if (res.success) {
        ElMessage.success(res.msg)
        close_from(row)
        GetListData()
        GetBD()
        loading.value = false
        btnloading.value = false;
      } else {
        ElMessage.error(res.msg)
        setTimeout(() => {
          loading.value = false;
          btnloading.value = false;
        }, 1500)
      }
    })
  }

  async function SendData(row) {
    let res = null
    let data = null;
    const datas = {
      "taskId": route.query.taskId,
      "planId": route.query.planId,
      piApplicant: row.piApplicant,
      piNumber: row.piNumber,
      ppName: row.ppName
    }
    if (row.getCar === 2) {

      res = await ProOBDDataObtainEmp(datas)
      if (res.success) {
        ElMessage.success(res.msg)
        GetListData()
      } else {
        ElMessage.error(res.msg)
      }
      return
    }
    if (row.getCar === 5) {
      res = await ProOBDDataObtainEmpState(datas);
      if (res.success) {
        ElMessage.success(res.msg)
        GetListData()
        data = {
          piApplicant: res.data.piApplicant
        }
        SendDataDate.value = res.data.empowerTime
      } else ElMessage.error(res.msg);
    }
    if (row.getCar === 6) {
      res = await ProProtectionGetCustomDetail(datas);
      if (res.success) {
        CartODB.value = true;
        ElMessage.success(res.msg);
        const { data } = res
        const datas = [
          {
            name: "姓名",
            value: data.piApplicant
          },
          {
            name: "年龄",
            value: data.applicantAge
          },
          {
            name: "性别",
            value: data.applicantSex
          },
          {
            name: "驾龄",
            value: data.drivingExperience
          },
          {
            name: "日均行驶时间(h)",
            value: data.travelTime
          },
          {
            name: "平均单次行驶时长(h)",
            value: data.singleTravelTime
          },
          {
            name: "日均夜间驾驶(min)",
            value: data.nightDrive
          },
          {
            name: "日均急加速次数",
            value: data.accCount
          },
          {
            name: "日均急刹车次数",
            value: data.brakeCount
          },
          {
            name: "日均急转弯次数",
            value: data.wheelCount
          },
          {
            name: "平均速度(Km/h)",
            value: data.averageSpeed
          },
          {
            name: "平均加速速度(m/s)",
            value: data.acceleration
          },
          {
            name: "行车车距过近次数",
            value: data.vehicleSpacing
          },
          {
            name: "牵扯碰撞次数",
            value: data.collision
          }
        ]
        CartODBData.datas = datas
        CartODBData.empowerTime = SpliceDate(data.empowerTime)
        GetListData()
      }
      else ElMessage.error(res.msg);
      return
    }
    statement.value = true;
    nextTick(() => {
      SendDataName.value = { ...row, ...data }
    })
  }

  async function SendDatas(row) {
    let res = null
    // let data = null;
    const data = {
      "taskId": route.query.taskId,
      "planId": route.query.planId,
      piNumber: row.piNumber,
      ppName: row.ppName,
      piApplicant: row.piApplicant
    }
    if (row.getHealth === 0 || row.getHealth === null) {
      res = await ProProtectionGetHealth(data)
      if (res.success) {
        ElMessage.success(res.msg)
        GetListDatas()
      } else {
        ElMessage.error(res.msg)
      }
      return
    } else if (row.getHealth === 2 || row.getHealth === 3) {
      // 查看
      const res = await ProProtectionGetAssured(qs.stringify({ PINumber: row.piNumber }));
      // console.log("show-desli", res)
      if (res.success) {
        ShowDetails.value = true;
        const { data } = res
        nextTick(() => {
          const datas = [
            {
              name: "姓名",
              value: data.assured
            },
            {
              name: "年龄",
              value: data.assuredAge
            },
            {
              name: "性别",
              value: data.assuredSex
            },
            {
              name: "民族",
              value: data.nation
            },
            {
              name: "身份证号码",
              value: data.idCard
            },
            {
              name: "电话号码",
              value: data.phone
            },
            {
              name: "婚姻状况",
              value: data.marriageState
            },
            {
              name: "省份",
              value: data.province
            },
            {
              name: "职业",
              value: data.career
            },
            {
              name: "教育程度",
              value: data.educationLevel
            },

            {
              name: "健康状况",
              value: data.healthState
            },
            {
              name: "是否吸烟",
              value: data.isSmoke
            },
            {
              name: "是否在肿瘤、心脑血管科室就诊过",
              value: data.isTumor
            },
            {
              name: "是否产生高额医疗费",
              value: data.isHigtAmount
            },
          ]
          MyDetails.datas = datas
          MyDetails.applyTime = SpliceDate(data.applyTime)

        })
      } else {
        ElMessage.error(res.msg)
      }
    }

  }

  // 发送授权声明
  async function SendAccredit() {
    if (!SendDataDate.value) {
      ElMessage.warning("请选择授权时间");
      return
    }
    const data = {
      "taskId": route.query.taskId,
      "planId": route.query.planId,
      piNumber: SendDataName.value.piNumber,
      empowerTime: SendDataDate.value,
      ppName: SendDataName.value.ppName,
      name: SendDataName.value.piApplicant
    };
    btnloading.value = true;
    const res = await ProOBDDataObtaAuth(data);
    if (res.success) {
      ElMessage.success(res.msg)
      CloseAccredit()
      GetListDatas()
      GetListData()
      GetBD()
      btnloading.value = false;
    } else {
      ElMessage.error(res.msg)
      setTimeout(() => { btnloading.value = false; }, 1500)
    }
  }
  // 关闭取消授权声明
  function CloseAccredit() {
    statement.value = false;
    SendDataDate.value = undefined;
    SendDataName.value = {}
  }
  // 关闭ODB监控行为窗口
  function CloseCartODB() {
    CartODB.value = false;
    CartODBData.datas = []
    CartODBData.empowerTime = ""
  }
  // 关闭申请窗口
  function close_from(row) {
    DialogVisible.value = false;
    row.resetFields();
  }

  // 获取数据
  async function GetBD() {
    const data = qs.stringify({
      "taskId": route.query.taskId,
      "planId": route.query.planId,
    });
    const res = await ProProtectionGetPINumber(data);
    if (res.success) {
      PINumber.value = res.data
    } else {
      ElMessage.error(res.msg);
    }
  }
  // 获取OBD数据
  async function GetListData() {
    const data = {
      "pageIndex": pagination.currentPage,
      "pageCount": pagination.pageSize,
      "taskId": route.query.taskId,
      "planId": route.query.planId,
    };
    const res = await ProProtectionGetOBDData(data);
    if (res.success) {
      dataList.value = res?.data?.items;
      pagination.total = res?.data?.totalCount;
      loading.value = false;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false; }, 1500)
    }
  }

  // 获取健康数据
  async function GetListDatas() {
    const data = {
      "pageIndex": paginations.currentPage,
      "pageCount": paginations.pageSize,
      "taskId": route.query.taskId,
      "planId": route.query.planId,
    };
    const res = await ProProtectionGetApplyHealth(data);
    if (res.success) {
      dataLists.value = res?.data?.items;
      paginations.total = res?.data?.totalCount;
      loadings.value = false;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loadings.value = false; }, 1500)
    }
  }
  onMounted(() => {
    GetBD()
    GetListData()
    GetListDatas()
  })
  return {
    rules,
    CartODB,
    newform,
    columns,
    dataList,
    loading,
    dataLists,
    loadings,
    PINumber,
    statement,
    stubimfrom,
    ShowDetails,
    MyDetails,
    btnloading,
    DialogVisible,
    SendDataName,
    pagination,
    paginations,
    CartODBData,
    SendDataDate,
    SendData,
    SendDatas,
    CloseCartODB,
    close_from,
    stubim_from,
    SendAccredit,
    CloseAccredit,
    handleSizeChange,
    handleSizeChanges,
    handleCurrentChanges,
    handleCurrentChange
  }
}
